var crypto = require('crypto');
var _ = require('lodash');

module.exports = {
  _ID_CHARS: 'ABCDEFGHJKLMNPQRSTUVWXY3456789',
  randomChars: function(length) {
    var s = '';
    for (var i = 0; i < length; i++) {
      s += this._ID_CHARS.charAt(_.random(0, this._ID_CHARS.length - 1));
    }
    return s;
  },
  /**
   * 将指定的数字转换成固定长度的 ID 值
   * @param id 原数字ID
   * @param length 转换后的长度
   * @returns {string} 超出范围会抛出异常
   */
  n2id: function(id, length) {
    var decimalLength = this._ID_CHARS.length;
    var chars = [];
    do {
      var mod = id % decimalLength;
      chars.unshift(this._ID_CHARS.charAt(mod));
      id = parseInt(id / decimalLength);
    } while (id > 0);
    if (chars.length > length) {
      throw new Error('id too large');
    }
    if (chars.length < length) {
      var count = length - chars.length;
      for (i = 0; i < count; i ++) {
        chars.unshift(this._ID_CHARS.charAt(0));
      }
    }
    return chars.join('');
  },
  /**
   * #n2id() 逆操作
   * @param sId
   * @returns {number}
   */
  id2n: function(sId) {
    var decimalLength = this._ID_CHARS.length;
    var nid = 0;
    for (var i = 0; i < sId.length; i++) {
      nid += this._ID_CHARS.indexOf(sId[i]) * Math.pow(decimalLength, sId.length - i - 1);
    }
    return nid;
  },
  uuid: function() {
    return Number(Date.now() + "" + parseInt(Math.random() * 900000 + 100000)).toString(36);
  },
  hash: function(origin) {
    return crypto.pbkdf2Sync(origin, 'e798633f0a9bbb4f245393aa7714b8d0', 1024, 16).toString('hex');
  }
}